package org.xhs.geomap.net
{
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import org.xhs.geomap.events.DataReadyEvent;
	
	public class BlockModel extends EventDispatcher
	{
		private var blocks:ArrayCollection;
		private var cities:ArrayCollection;		
		private var db:ArrayCollection;
		private var cityIndex:int=0;
		private var blockIndex:int=0;
		private static  var _bm:BlockModel;
		
		public function BlockModel()
		{
			loadBlockXML();
		}
		
		public static function getInstance():BlockModel
		{
			if(_bm == null)
			{
				_bm = new BlockModel();
			}
			return _bm;				
		}
		
		private function loadBlockXML():void
		{
			var service:HTTPService = new HTTPService(); 
			service.url = "testdata/Block.xml";
			service.send(); 
			service.addEventListener(ResultEvent.RESULT,onXMLResult); 
		}
		
		private function onXMLResult(evt:ResultEvent):void
		{
			db = evt.result.citylist.city;		
			dispatchEvent(new DataReadyEvent("ready"));	
		}
		
		public function getCities():ArrayCollection
		{
			var temp:ArrayCollection = new ArrayCollection();
			for(var i:int = 0;i < db.length;i++)
			{
				var o:Object = new Object();
				o.label = db.getItemAt(i).name;
				o.data = db.getItemAt(i).value;
				temp.addItem(o);
			}
			cities = temp;
			return temp;
		}
		
		public function getBlocksAtCity(citycode:String):ArrayCollection
		{
			var temp:ArrayCollection = new ArrayCollection();
			var index:int = -1;
			for(var j:int = 0;j < db.length;j++)
			{
				if(db.getItemAt(j).value == citycode)
				{
					index = j;
					break;
				}
			}
			var b:ArrayCollection = db.getItemAt(index).block;
			for(var i:int = 0;i < b.length;i++)
			{
				var o:Object = new Object();
				o.label = b.getItemAt(i).name;
				o.data = b.getItemAt(i).value;
				temp.addItem(o);
			}
			blocks = temp;
			return temp;
		}
		
		public function setCityIndex(index:int):void
		{
			cityIndex = index;
		}
		
		public function setBlockIndex(index:int):void
		{
			blockIndex = index;
		}
		
		public function getSeletedCityName():String
		{
			return cities.getItemAt(cityIndex).label;
		}
		
		public function getSeletedCityCode():String
		{
			return cities.getItemAt(cityIndex).data;			
		}
		
		public function getSeletedBlockName():String
		{
			return blocks.getItemAt(blockIndex).label;
		}
		
		public function getSeletedBlockCode():String
		{
			return blocks.getItemAt(blockIndex).data;
		}
	}
}